package com.fencing_squad.homo.slice;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.fencing_squad.homo.ResourceTable;
import com.fencing_squad.homo.util.CustomComponent;
import com.fencing_squad.homo.util.Data;
import com.fencing_squad.homo.util.ImageLoader;
import com.fencing_squad.homo.util.Network;
import de.hdodenhof.circleimageview.CircleImageView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.InputStream;
import java.util.Base64;

public class UserDetailSlice extends AbilitySlice {
    private Text nickname;
    private Text uid;
    private CircleImageView icon;
    private Button signOut;
    private Component idCard;
    private Component nickName;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent((ComponentContainer) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_user_detail, null, false));

        initConfig();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void initConfig() {
        nickname = (Text) findComponentById(ResourceTable.Id_userDetailNickname);
        uid = (Text) findComponentById(ResourceTable.Id_userDetailUID);
        icon = (CircleImageView) findComponentById(ResourceTable.Id_userDetailIcon);
        signOut = (Button) findComponentById(ResourceTable.Id_signOut);
        idCard = findComponentById(ResourceTable.Id_idCard);
        nickName = findComponentById(ResourceTable.Id_userDetailUID);

        nickname.setText(Data.Account.nickname.equals("") ? "昵称" : Data.Account.nickname);
        uid.setText(Data.Account.uid.equals("") ? "UID:--" : "UID:"+Data.Account.uid);
        Glide.with(this).load(Data.Account.avatar).listener(ImageLoader.fail(icon, ResourceTable.Media_icon)).into(icon);
        signOut.setClickedListener(component -> {
            signOut();
        });
        idCard.setClickedListener(component -> {
            changeIdCard();
        });
        nickName.setClickedListener(component -> {
            changeNickName();
        });
    }

    private void signOut() {
        Data.Account.clear();
        terminate();
    }

    private void changeIdCard(){
        selectImg(200);
    }

    private void changeNickName(){

    }

    private void selectImg(int code) {
        requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE"}, code);
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
        intent.setOperation(opt);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent, code);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == 200) {
            String url = resultData.getUriString();
            byte[] img = getImage(url);
            if (img == null) {
                CustomComponent.getDialog(this, "图片上传错误，请重试", null, null).show();
                return;
            }

            JSONObject object = new JSONObject();
            object.put("id_card_stream", Base64.getEncoder().encodeToString(img));
            Network.postJson("/user/real_name_auth", object.toJSONString(), this::resolve, this::reject);
        }
    }

    private void resolve(JSONObject object) {
        CustomComponent.getToastDialog(this, "认证成功").show();
        Data.Account.validToken();
    }

    private void reject(int code, String message) {
        if(code == 404) {
            CustomComponent.getDialog(this, message, null, null).show();
        }
        else {
            System.out.println(message);
        }
    }

    public byte[] getImage(String value) {
        //定义数据能力帮助对象
        DataAbilityHelper helper = DataAbilityHelper.creator(this);
        //定义图片来源对象
        ImageSource imageSource = null;
        //获取选择的Img对应的Id
        String chooseImgId = null;
        //如果是选择文件则getUriString结果为content://com.android.providers.media.documents/document/image%3A30，其中%3A是":"的URL编码结果，后面的数字就是image对应的Id
        //如果选择的是图库则getUriString结果为content://media/external/images/media/30，最后就是image对应的Id
        //这里需要判断是选择了文件还是图库
        if(value.lastIndexOf("%3A")!=-1){
            chooseImgId = value.substring(value.lastIndexOf("%3A")+3);
        }
        else {
            chooseImgId = value.substring(value.lastIndexOf('/')+1);
        }
        //获取图片对应的uri，由于获取到的前缀是content，我们替换成对应的dataability前缀
        Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,chooseImgId);
        try {
            //读取图片
            FileDescriptor fd = helper.openFile(uri, "r");
            InputStream in = helper.obtainInputStream(uri);
            byte[] img = new byte[in.available()];
            System.out.println(in.available());
            in.read(img);
            in.close();
            return img;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (imageSource != null) {
                imageSource.release();
            }
        }
        return null;
    }
}
